﻿@page "/checkout"
@using Microsoft.AspNetCore.Authorization
@rendermode InteractiveWebAssembly
@attribute [Authorize]
@inject OrderState OrderState
@inject IJSRuntime JSRuntime
@inject IRepository Repository
@inject NavigationManager NavigationManager


<PageTitle>Blazing Pizza - Checkout</PageTitle>

<div class="main">

	<EditForm EditContext="EditContext" OnValidSubmit="PlaceOrder">

		<div class="checkout-cols">
			<div class="checkout-order-details">
				<h4>Review order</h4>
				<OrderReview Order="OrderState.Order" />
			</div>

			<div class="checkout-delivery-address">
				<h4>Deliver to...</h4>
				<AddressEditor Address="OrderState.Order.DeliveryAddress" />
			</div>

		</div>

		<button class="checkout-button btn btn-warning" type="submit">
			Place order
		</button>

		<DataAnnotationsValidator />
		<ValidationSummary />

	</EditForm>

</div>

@code {

	public EditContext EditContext { get; set; } = new EditContext(new Order());

	override protected async Task OnAfterRenderAsync(bool first)
	{

		if (first)
		{
			await OrderState.GetStateFromLocalStorage(JSRuntime);

			EditContext = new EditContext(OrderState.Order.DeliveryAddress);
			EditContext.SetFieldCssClassProvider(new BootstrapFieldClassProvider());

			StateHasChanged();
		}

	}

	async Task PlaceOrder()
	{
		var newOrderId = await Repository.PlaceOrder(OrderState.Order);
		OrderState.ResetOrder();
		NavigationManager.NavigateTo($"myorders/{newOrderId}");
	}
}